<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="auto">
      <el-form-item label="批次号" prop="bachcode">
        <el-input v-model="queryParams.bachcode" placeholder="请输入批次号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status">
          <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="批次类型" prop="type">
        <el-input v-model="queryParams.type" placeholder="请输入批次类型" clearable />
      </el-form-item>
      <el-form-item label="时间范围" prop="type">
        <el-date-picker v-model="queryParams.time" @change="queryParamsTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-search" size="mini" @click="resHandleQuery">重置</el-button>
      </el-form-item>

    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleAddBatchCode" v-hasPermi="['produce:criticalBatch:add']">生成批次号</el-button>
        <el-button type="primary" plain icon="el-icon-print" size="mini" @click="handlePrint" v-hasPermi="['produce:criticalBatch:print']">打印</el-button>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['produce:criticalBatch:export']">导出</el-button>
        </el-col>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="qualityList" height="calc(100vh - 240px)" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="序号" align="center" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="bachcode">
        <template slot-scope="scope">
          <el-button @click="handleViewBatcode(scope.row)" type="text" size="small">{{ scope.row.bachcode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="批次类型" align="center" prop="type" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-show="scope.row.status === 1">已绑定</span>
          <span v-show="scope.row.status === 0">未绑定</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定数量" align="center" prop="bindingCount">
        <template slot-scope="scope">
          <span v-show="!scope.row.bindingCount">0</span>
          <span v-show="scope.row.bindingCount">{{ scope.row.bindingCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="handleBand(scope.row)" type="text" size="small" v-hasPermi="['produce:criticalBatch:bind']">绑定</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <!-- 查看暂停记录页面 -->
    <el-drawer title="详情" :visible.sync="suspendOpen" size="80%" @close="cancel">
      <el-table :data="detailList">
        <el-table-column label="检验单id" align="center" prop="inspectionId" />
        <el-table-column label="检验类型" align="center" prop="indexType" />
        <el-table-column label="检验项名称" align="center" prop="indexName" />
        <el-table-column label="检验项结果" align="center" prop="checkResult">
          <template slot-scope="scope">
            <span v-show="scope.row.checkResult === 0">不合格</span>
            <span v-show="scope.row.checkResult === 1">合格</span>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
    <el-dialog title="绑定序列号" :visible.sync="openDialog" width="800px" append-to-body>

      <div>
        <div style="width:100%;display:flex;">序列号：
          <!-- @keyup.enter.native="querySnCodeInfo"   @input="addDomain"-->
          <el-input v-model.trim="serialNumber" type="textarea" placeholder="注意:此处如果是复制过来的，请加英文版的逗号(,)" style="flex:1;margin-right: 10px" @input="addDomain" clearable></el-input>
        </div>
        <el-divider content-position="center">已扫序列号</el-divider>
        <div style="display:flex;align-items:center;">
          <div style="    flex: 0 0 150px;text-align:center;">序号</div>
          <div style="    flex: 1;text-align:center;">序列号</div>
          <div style="    flex: 0 0 150px;text-align:center;">操作</div>
        </div>
        <div v-for="(item, index) in scanSerialNumberList" :key="item + index" style="display:flex;align-items:center;">
          <div style="    flex: 0 0 150px;text-align:center;">{{ index + 1 }}</div>
          <div style="    flex: 1;text-align:center;">{{ item }}</div>
          <div style="    flex: 0 0 150px;text-align:center;"><el-button type="text" @click.prevent="removeDomain(item, index)">删除</el-button></div>

        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelBind">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="已绑定序列号" :visible.sync="openBindCodeDialog" width="800px" append-to-body>
      <div>
        <div style="display:flex;align-items:center;">
          <div style="    flex: 0 0 150px;text-align:center;">序号</div>
          <div style="    flex: 1;text-align:center;">序列号</div>
        </div>
        <div v-for="(item, index) in scanSerialNumberList" :key="item + index" style="display:flex;align-items:center;">
          <div style="    flex: 0 0 150px;text-align:center;">{{ index + 1 }}</div>
          <div style="    flex: 1;text-align:center;padding: 12px 0;">{{ item }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openBindCodeDialog = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="生成批次号" :visible.sync="openBatchCodeDialog" width="800px" append-to-body>
      <el-form ref="bachcodeForm" :model="bachcodeForm" label-width="auto" :rules="bachcodeFormRules">
        <el-form-item label="数量" prop="bindingCount">
          <el-input v-model.number="bachcodeForm.bindingCount"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input v-model="bachcodeForm.type"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBachcodeForm">确 定</el-button>
        <el-button @click="openBatchCodeDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  WmKeyDevicesBinding,
  binding,
  addWmKeyDevicesBinding,
  getSerialList,
  printBatchCode,
} from "@/api/mes/pro/keyMatchManagement.js";
import axios from "axios";
import moment from "moment";
export default {
  name: "KeyMatchManagement",
  data() {
    return {
      scanSerialNumberList: [111, 2222],
      serialNumber: null,
      bachcodeFormRules: {
        bindingCount: [
          { required: true, message: "请填写活动形式", trigger: "blur" },
        ],
        type: [{ required: true, message: "请填写活动形式", trigger: "blur" }],
      },
      bachcodeForm: {
        bindingCount: null,
        type: null,
      },
      openBatchCodeDialog: false,
      activeRow: {},
      openDialog: false,
      openBindCodeDialog: false,
      statusList: [
        { value: 1, label: "已绑定" },
        { value: 0, label: "未绑定" },
      ],
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bachcode: null, //批次号
        status: null, //状态  0，未绑定，1已绑定
      },
      suspendOpen: false,
      qualityList: [],
      detailList: [],
      dynamicValidateForm: {
        serialNumberList: [
          {
            value: "",
          },
        ],
      },
      multipleSelection: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //重置
    resHandleQuery() {
      this.queryParams = {}
    },
    // 时间选择器事件
    queryParamsTime(val) {
      if (Array.isArray(val) && val.length === 2) {
        // 将选择的开始日期加上 "00:00:00"
        this.queryParams.timeBegin = this.formatDate(new Date(val[0]), '00:00:00');
        // 将选择的结束日期加上 "23:59:59"
        this.queryParams.timeEnd = this.formatDate(new Date(val[1]), '23:59:59');
      } else {
        this.queryParams.timeBegin = null;
        this.queryParams.timeEnd = null;
      }
    },

    // 格式化日期的方法，拼接时间部分
    formatDate(date, time) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      // 拼接日期与时间
      return `${year}-${month}-${day} ${time}`;
    },
    handleViewBatcode(row) {
      this.openBindCodeDialog = true
      getSerialList(row.bachcode).then((res) => {
        this.scanSerialNumberList = res.data ? res.data : [];
      });
    },
    handlePrint() {
      console.log(333);
      console.log(this.multipleSelection);
      if (!this.multipleSelection.length) {
        this.$message.error("请先勾选批次号！");
        return;
      }
      const params = this.multipleSelection.map((item) => {
        const obj = {
          type: item.type,
          bachcode: item.bachcode,
        };
        return obj;
      });
      // printBatchCode(params).then(res => {
      //   if(res.code === 200){
      //     this.$message.success('打印成功')
      //   }
      // })
      // axios
      // .post("http://192.168.42.184:8899/hici/print/wmKeyDevice", params)
      // .then(function (response) {
      //   console.log(response);
      // })
      // .catch(function (error) {
      //   console.log(error);
      // });
      printBatchCode(params).then(res => {
        console.log(res)
      })
    },
    handleSelectionChange(val) {
      console.log(111);
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    submitBachcodeForm() {
      this.$refs["bachcodeForm"].validate((valid) => {
        if (valid) {
          addWmKeyDevicesBinding(this.bachcodeForm).then((res) => {
            if (res.code === 200) {
              this.$message.success("提交成功");
              this.openBatchCodeDialog = false;
              this.getList();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleAddBatchCode() {
      this.bachcodeForm = {
        bindingCount: null,
        type: null,
      };
      this.openBatchCodeDialog = true;
    },
    cancelBind() {
      this.openDialog = false;
      this.dynamicValidateForm.serialNumberList = [
        {
          value: "",
        },
      ];
    },
    submitForm() {
      const params = {
        id: this.activeRow.id,
        bachcode: this.activeRow.bachcode,
        serialNumberList: this.scanSerialNumberList,
        status: this.activeRow.status
      };
      binding(params).then((res) => {
        console.log(123, res);
        if (res.code === 200) {
          this.$message.success("绑定成功");
          this.openDialog = false;
          this.getList();
        }
      });
    },
    handleBand(row) {
      console.log(333, row.bachcode);
      this.scanSerialNumberList = []
      this.serialNumber = null
      this.openDialog = true;
      this.activeRow = row;
      getSerialList(row.bachcode).then((res) => {
        this.scanSerialNumberList = res.data ? res.data : [];
      });
    },
    removeDomain(item) {
      var index = this.scanSerialNumberList.indexOf(item);
      if (index !== -1) {
        this.scanSerialNumberList.splice(index, 1);
      }
    },
    addDomain() {
      if (this.serialNumber) {
        // 使用 Set 去重，支持换行符 (\n) 和逗号 (,) 作为分隔符
        let arr = Array.from(
          new Set(
            this.serialNumber
              .split(/[\n,]+/) // 按换行符或逗号分割
              .map(item => item.trim()) // 去除前后空格
              .filter(item => item) // 过滤掉空字符串
          )
        );

        console.log("解析后的去重数组:", arr);

        if (!this.scanSerialNumberList) {
          this.scanSerialNumberList = arr;
        } else {
          // 找出 scanSerialNumberList 里已经存在的重复项
          let duplicateItems = arr.filter(item => this.scanSerialNumberList.includes(item));
          let newItems = arr.filter(item => !this.scanSerialNumberList.includes(item));

          if (newItems.length > 0) {
            this.scanSerialNumberList = this.scanSerialNumberList.concat(newItems);
            console.log("添加的新序列号：", newItems);
          }

          if (duplicateItems.length > 0) {
            this.$message.error(`以下序列号已存在: ${duplicateItems.join(", ")}`);
          }
        }

        // 清空输入框
        this.serialNumber = null;
      }
    },


    handleQuery() {
      this.getList();
    },
    /** 查询生产报工记录列表 */
    getList() {
      this.loading = true;
      WmKeyDevicesBinding(this.queryParams)
        .then((response) => {
          this.loading = false;
          if (response.rows && response.rows.length) {
            this.qualityList = response.rows;
            this.total = response.total;
          } else {
            this.qualityList = [];
            this.total = 0;
          }
        })
        .catch((err) => {
          this.qualityList = [];
          this.total = 0;
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    //查看详情
    handleDetails(row) {
      this.detailList = [];
      this.suspendOpen = true;
      getSerialList(row.bachcode).then((response) => {
        if (response.data && response.data.length) {
          this.detailList = response.data;
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.multipleSelection.length == 0) {
        this.$message.error("请勾选需要导出的数据");
        return false
      }
      // 获取 multipleSelection 中所有选中项的 bachcode
      const bachcodes = this.multipleSelection.map(item => item.bachcode);
      console.log(bachcodes);

      this.download(
        "mes/wm/WmKeyDevicesBinding/export",
        {
          "bachcode": bachcodes.join(",")
        },
        `关键器件批次管理_${moment(new Date()).format('yyyyMMDDHHmmss')}.xlsx`
      );
    },
  },
};
</script>
